package cn.rui.common;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.rui.myexception.CityQueryException;
import cn.rui.myexception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常
 * @author 徽州大都督
 * @date 2021/05/13
 */
@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result RuntimeException(RuntimeException ex){
        // 打印堆栈，以供调试
        return Result.getFailure ("系统错误!");
    }


    /**
     * 未登录异常
     * @param nle
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public String  NotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response){
        // 打印堆栈，以供调试
        return "login";
    }


    /**
     * 无权限
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(NotPermissionException.class)
    @ResponseBody
    public Result NotPermissionException(NotPermissionException ex){
        return Result.getFailure ("无权限");
    }


    @ExceptionHandler(DisableLoginException.class)
    @ResponseBody
    public Result DisableLoginException(DisableLoginException ex){
        return Result.getFailure (ex.getMessage ());
    }

    //自定义异常
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result MyException(MyException ex){
        return Result.getFailure (ex.getMessage ());
    }

    //城市信息查询失败
    @ExceptionHandler(CityQueryException.class)
    @ResponseBody
    public Result CityQueryException(CityQueryException ex){
        return Result.getFailure (ex.getMessage ());
    }

}
